package com.adresvseti.wallpaperoid.services;

import java.io.IOException;
import java.io.InputStream;

import com.adresvseti.wallpaperoid.utils.BitmapUtil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;

/**
 * Decodes and resizes bitmap.
 *
 */
public class DecodeBitmapTask extends AsyncTask<InputStream, Void, Bitmap> {

	private final IDecodeBitmapCallback callback;
	private final int targetWidth;
	private final int targetHeight;
	
    private Bitmap result;
    

    public DecodeBitmapTask(int targetWidth, int targetHeight, IDecodeBitmapCallback callback) {
        
    	this.callback = callback;
    	this.targetWidth = targetWidth;
    	this.targetHeight = targetHeight;
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(InputStream... params) {
        InputStream is = params[0];
        
        try
        {
        	byte[] data = BitmapUtil.convertInputStreamToByteArray(is);
        	
        	// First decode with inJustDecodeBounds=true to check dimensions
        	final Options options = new BitmapFactory.Options();
        	options.inJustDecodeBounds = true;
        	BitmapFactory.decodeByteArray(data, 0, data.length, options);

        	// Calculate inSampleSize
        	options.inSampleSize = BitmapUtil.calculateInSampleSize(options, targetWidth, targetHeight);

        	// Decode bitmap with inSampleSize set
        	options.inJustDecodeBounds = false;
        	result = BitmapFactory.decodeByteArray(data, 0, data.length, options);

        	return result;
        } catch (IOException e) {
			return null;
		}
        finally {
        	if (is != null) {
        		
        		try {
					is.close();
				} catch (IOException e) {
					is = null;
				}
        		
        	} 
        }
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
    	
    	callback.success(bitmap);
    	
    }
	
}
